<template>
	<view class="header">
		<uni-icons type="left" size="25" @click="back"></uni-icons>
		<view class="title">我的宝宝</view>
		<view class="add-btn" @click="addbaby">+添加宝宝</view>
	</view>
	<view>
		<uni-list :border="true">
			<uni-list-chat 
				v-for="baby in babyList" 
				:key="baby.id" 
				:avatar-circle="true"  
				:title="baby.nickname"  
				:avatar="baby.avatar || '../../static/uni.png'"  
				:note="calculateAge(baby.birthday)"  
				badge-positon="left" 
				:clickable="true" 
				@click="navigateToBabyDetail(baby.id)" 
			>
				<view class="chat-custom-right">
					<uni-icons type="right" color="#999" size="18" ></uni-icons>
				</view>
			</uni-list-chat>				
		</uni-list>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const back =()=>{
	uni.switchTab({
		url: '/pages/user/my/my'
	});
}

const addbaby =()=>{
	uni.navigateTo({
		url: '/pages/baby/information1/information1' 
	});
}

// 定义响应式数据
const babyList = ref([]);

//获取宝宝列表数据
const fetchBabyList = async () => {
	
	uni.request({
	    method: 'GET',
	    url: 'http://localhost:9100/api/baby/selectList',
	    header: {
	        'bece_token': uni.getStorageSync('bece_token') 
	    },
	    success: (res) => {
	        console.log(res.data);
			if (res.data.code == 200) {
				babyList.value = res.data.data;
				
			} else {
				uni.showToast({
					title: res.data.msg,
					duration: 2000
				});
			}
	    }
	});
};

// 计算宝宝年龄
const calculateAge = (birthday) => {
	if (!birthday) return '';

	const birth = new Date(birthday);
	const now = new Date();

	let months = (now.getFullYear() - birth.getFullYear()) * 12;
	months += now.getMonth() - birth.getMonth();

	if (months < 12) {
		return `${months}个月`;
	} else {
		const years = Math.floor(months / 12);
		const remainingMonths = months % 12;
		return remainingMonths > 0 ? 
		  `${years}岁${remainingMonths}个月` : 
		  `${years}岁`;
	}
};

// 跳转到对应的宝宝首页
const navigateToBabyDetail = (id) => {

	// uni.setStorageSync('birthDay', birthday);
	// console.log(birthday)
	uni.setStorageSync('babyId', id);
	uni.switchTab({
		url: '/pages/home/home?id=${id}'
	});
};

// 页面加载时获取数据
onMounted(() => {
	fetchBabyList();
});
	
</script>

<style scoped>
.header {
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 14rpx;
	position: relative;
	border-bottom: 4rpx solid #f2f2f2;
}
.title {
	font-size: 32rpx;
	font-weight: bold;
	position: absolute;
	left: 310rpx;
}
.add-btn {
	font-size: 30rpx;
	color: blue;
	position: absolute;
	right: 36rpx
}
	    
.chat-custom-right {
	  height: 100%;
	  display: flex;
	  align-items: center; /* 垂直居中 */
	  padding-right: 10rpx; /* 添加右边距 */
}

.chat-custom-text {
	font-size: 12px;
	color: #999;
}		
		   
</style>
